import os.path

import pandas as pd
from langchain_core.documents import Document

from api_server.db.repository import update_file_status
from api_server.knowledge_base.kb_service.base import KBServiceFactory
from api_server.knowledge_base.utils import KnowledgeFile, get_file_path
from api_server.db.base import engine
from api_server.db.repository.z_rectify_repository import delete_rectify


def hand_gz_file(filename, user_info=None):
    knowledge_base_name = 'sjzgqrzsk'
    df = pd.read_excel(filename)
    df = df[["整改事项编号", "审计报告名称", "审计报告发布日期", "被审计单位", "问题类型", "问题概要", "问题详细描述",
             "审计风险金额(元)", "整改建议", "审计组联系人", "责任部门", "整改落实情况", "整改结果确认"]]
    data_column = {"整改事项编号": "audit_code", "审计报告名称": "audit_report_name",
                   "审计报告发布日期": "audit_report_date",
                   "被审计单位": "audit_unit", "问题类型": "question_type",
                   "问题概要": "question_summary", "问题详细描述": "question_detail",
                   "审计风险金额(元)": "audit_money", "整改建议": "rectify_advice",
                   "审计组联系人": "audit_manager", "责任部门": "audit_dept",
                   "整改落实情况": "rectify_hand", "整改结果确认": "recitify_result"}
    df.rename(columns=data_column, inplace=True)
    #
    def hand_item(x, docs=[], codes=[]):
        detail = x['question_detail']
        code = x['audit_code']
        name = x['audit_report_name']
        metadata = {"source": name, "row": 1, "code": code, 'doc_type': 'zg'}
        doc = Document(page_content=detail, metadata=metadata)
        codes.append(code)
        docs.append(doc)

    docs = []
    codes = []
    df.apply(lambda x: hand_item(x, docs, codes), axis=1)
    # 进行向量化
    filepath = '%s.md' % get_file_path(knowledge_base_name, os.path.basename(filename).split('.')[0])
    with open(filepath, 'w', encoding='utf-8') as file:
        file.write('# 整改清单文件内容 \n')
        for doc in docs:
            metadata = doc.metadata
            name = metadata['source']
            content = doc.page_content
            file.write('## %s \n' % name)
            file.write(' %s \n' % content)
    kb_file = KnowledgeFile(filename=os.path.basename(filepath),
                            knowledge_base_name=knowledge_base_name)
    kb_file.splited_docs = docs
    kb = KBServiceFactory.get_service_by_name(knowledge_base_name)
    kb.update_doc_by_text(kb_file, not_refresh_vs_cache=True, user_info=user_info)
    # 先清除旧数据
    delete_rectify(codes=codes)
    # 保存到数据库
    df.to_sql('z_rectify_data', con=engine, if_exists='append', index=False)
    return kb_file.filename


if __name__ == '__main__':
    # path = r'D:\mywork\文档\smart_audit\整改\广东整改台账20240624170433.xlsx'
    # hand_gz_file(path)

    update_file_status(status=2,kb_name='sjzgqrzsk',filename='广东整改台账20240624170433.md')
